package info.batcloud.fanli.api.controller;

import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.settings.UrlMappingSetting;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.inject.Inject;

@Controller
@RequestMapping("/webpage")
public class WebpageController {

    @Inject
    private SystemSettingService systemSettingService;

    @GetMapping
    public String visit(@RequestParam(required = false) String url,
                        @RequestParam(required = false) String code, @RequestParam(required = false) String params) {
        if (StringUtils.isNotBlank(url)) {
            return "redirect:" + url;
        }

        UrlMappingSetting urlMappingSetting = systemSettingService.findActiveSetting(UrlMappingSetting.class);
        UrlMappingSetting.UrlMapping um = urlMappingSetting.getUrlByCode(code);
        if (um == null) {
            return null;
        }
        url = um.getUrl();
        if(StringUtils.isNotBlank(params)) {
            if(url.indexOf("?") != -1) {
                url += "&" + params;
            } else {
                url += "?" + params;
            }
        }
        return "redirect:" + url;
    }

}
